import sys
import os
import json
import webbrowser
import utils.botChat as bc
from utils.dbTreat import db
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout,
    QHBoxLayout, QPushButton, QLineEdit, QLabel, QTextEdit,
    QListWidget, QListWidgetItem, QComboBox, QMessageBox,
    QSplitter, QFrame, QInputDialog, QDialog, QTableWidget,
    QTableWidgetItem, QHeaderView, QGroupBox, QCheckBox
)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont


# ==================== 配置管理器（基于 JSON）====================
class SettingsManager:
    """管理应用的 JSON 配置文件"""

    def __init__(self):
        self.app_dir = os.path.dirname(os.path.abspath(__file__))
        self.config_dir = os.path.join(self.app_dir, "config")
        self.config_file = os.path.join(self.config_dir, "settings.json")

        os.makedirs(self.config_dir, exist_ok=True)

        self.default_settings = {
            "minimize_on_close": False
        }

        self.settings = self.load_settings()
        # 更新日志
        # 微信列表
        # 群列表
        # 插件列表

    def load_settings(self):
        """
        读取配置文件
        :return:
        """
        if not os.path.exists(self.config_file):
            self.save_settings(self.default_settings)
            return self.default_settings.copy()

        try:
            with open(self.config_file, "r", encoding="utf-8") as f:
                data = json.load(f)
                for k, v in self.default_settings.items():
                    if k not in data:
                        data[k] = v
                return data
        except (json.JSONDecodeError, IOError):
            return self.default_settings.copy()

    def save_settings(self, data):
        """
        保存配置文件
        :param data:
        :return:
        """
        try:
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
        except IOError as e:
            print(f"无法保存配置文件: {e}")

    def should_minimize_on_close(self):
        """
        返回是否最小化关闭
        :return:
        """
        return self.settings.get("minimize_on_close", False)

    def set_minimize_on_close(self, value):
        """
        设置是否最小化关闭
        :param value:
        :return:
        """
        self.settings["minimize_on_close"] = bool(value)
        self.save_settings(self.settings)


# ==================== 主窗口 ====================
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("pyBotAuto")
        self.setFixedSize(1000, 700)
        self.settings_manager = SettingsManager()

        # 应用美化样式
        self.apply_styles()

        # 微信列表数据
        self.wechat_list_data = [
            {"name": "张三的微信", "login_time": "2024-04-05 10:00", "duration": "2h15m",
             "pid": 1234, "status": "运行中", "recv": 45, "send": 12},
            {"name": "李四的微信", "login_time": "2024-04-05 11:30", "duration": "45m",
             "pid": 5678, "status": "暂停", "recv": 8, "send": 3},
        ]

        # 插件列表数据
        self.plugin_data = [
            {"name": "自动回复插件", "version": "1.0.0", "author": "开发者A", "desc": "自动回复消息", "status": "启用"},
            {"name": "群发助手", "version": "0.9.5", "author": "开发者B", "desc": "群发消息", "status": "禁用"},
            {"name": "防撤回插件", "version": "1.1.0", "author": "开发者C", "desc": "防止消息被撤回", "status": "启用"},
        ]

        self.master_wechat_name = ""
        self.current_selected_wechat = None

        self.init_ui()

    def apply_styles(self):
        style = """
        QMainWindow, QDialog {
            background-color: #f0f0f0;
            font-family: "Microsoft YaHei", "SimSun", sans-serif;
        }
        QTabWidget::pane {
            border: 1px solid #c8c8c8;
            background: white;
            border-radius: 6px;
            padding: 10px;
        }
        QTabBar {
            font-size: 12px;
            font-weight: bold;
            color: #333;
        }
        QTabBar::tab {
            background: #e8e8e8;
            color: #333;
            padding: 10px 20px;
            margin-right: 2px;
            border-top-left-radius: 6px;
            border-top-right-radius: 6px;
        }
        QTabBar::tab:selected {
            background: #409eff;
            color: white;
        }
        QPushButton {
            background-color: #409eff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 12px;
        }
        QPushButton:hover {
            background-color: #66b1ff;
        }
        QPushButton:pressed {
            background-color: #3a7bc8;
        }
        QLineEdit, QTextEdit, QComboBox, QListWidget, QTableWidget {
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 6px;
            background-color: #ffffff;
            font-size: 12px;
        }

        /* ============ 修正下拉菜单高度与悬停问题 ============ */
        QComboBox QAbstractItemView {
            border: 1px solid #ccc;
            background-color: white;
            color: #333;
            selection-background-color: #409eff;
            selection-color: white;
            outline: none;
            min-height: 30px;
        }

        QComboBox::item {
            color: #333;
            background-color: white;
        }

        QComboBox::item:hover {
            color: #000;
            background-color: #e6f3ff;
        }

        QComboBox::item:selected {
            color: white;
            background-color: #409eff;
        }
        """
        self.setStyleSheet(style)

    def init_ui(self):
        self.tabs = QTabWidget()
        self.setCentralWidget(self.tabs)

        self.create_home_tab()
        self.create_wechat_tab()
        self.create_group_tab()
        self.create_entertainment_tab()
        self.create_settings_tab()

    def create_home_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        self.btn_website = QPushButton("🌐 官网")
        self.btn_website.setFixedWidth(120)
        self.btn_website.setToolTip("访问项目官网")
        self.btn_website.clicked.connect(lambda: webbrowser.open("https://gitee.com/BlackCarp/py-bot-auto"))
        btn_layout.addWidget(self.btn_website)
        btn_layout.addStretch()
        layout.addLayout(btn_layout)

        log_group = QGroupBox("📄 更新日志")
        log_layout = QVBoxLayout()
        self.log_edit = QTextEdit()
        self.log_edit.setReadOnly(True)
        self.log_edit.setLineWrapMode(QTextEdit.WidgetWidth)
        self.log_edit.setFont(QFont("SimSun", 10))
        self.log_edit.setStyleSheet("QTextEdit { background-color: #f9f9f9; }")
        # 添加日志
        self.log_edit.setText(
            "【v1.2.0】 - 2025-04-05\n"
            "• 优化微信登录检测机制\n"
            "• 新增群聊消息统计\n"
            "• 修复插件加载失败问题\n\n"
            "【v1.1.0】 - 2025-03-20\n"
            "• 支持多微信管理\n"
            "• 添加插件框架"
        )
        log_layout.addWidget(self.log_edit)
        log_group.setLayout(log_layout)
        layout.addWidget(log_group)

        layout.addStretch()
        tab.setLayout(layout)
        self.tabs.addTab(tab, "主页")

    def create_wechat_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(10)

        # 主人微信设置
        top_layout = QHBoxLayout()
        self.wechat_input = QLineEdit()
        self.wechat_input.setPlaceholderText("请输入主人微信名, 功能暂未实现")
        self.save_master_btn = QPushButton("保存")
        self.save_master_btn.clicked.connect(self.save_master_name)
        top_layout.addWidget(self.wechat_input)
        top_layout.addWidget(self.save_master_btn)
        layout.addLayout(top_layout)

        # 控制按钮
        ctrl_layout = QHBoxLayout()
        self.refresh_btn = QPushButton("🔄 刷新")
        self.setup_btn = QPushButton("⚙️ 设置")
        self.setup_btn.setEnabled(False)
        self.setup_btn.setToolTip("请选择一个微信账号进行设置")
        self.refresh_btn.clicked.connect(self.refresh_wechat_list)
        self.setup_btn.clicked.connect(self.open_setup_window)
        ctrl_layout.addWidget(self.refresh_btn)
        ctrl_layout.addStretch()
        ctrl_layout.addWidget(self.setup_btn)
        layout.addLayout(ctrl_layout)

        # 微信表格
        self.wechat_table = QTableWidget()
        self.wechat_table.setColumnCount(7)
        self.wechat_table.setHorizontalHeaderLabels(
            ["微信名", "登录时间", "运行时长", "PID", "状态", "收消息", "发消息"])
        self.wechat_table.verticalHeader().setVisible(False)
        self.wechat_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.wechat_table.setSelectionBehavior(QTableWidget.SelectRows)
        # self.wechat_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.wechat_table.horizontalHeader().setSectionsMovable(False)
        self.wechat_table.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.wechat_table.setColumnWidth(0, 180)
        self.wechat_table.setColumnWidth(1, 150)
        self.wechat_table.setColumnWidth(2, 120)
        self.wechat_table.setColumnWidth(3, 120)
        self.wechat_table.setColumnWidth(4, 120)

        self.wechat_table.selectionModel().selectionChanged.connect(self.on_wechat_table_selected)
        layout.addWidget(self.wechat_table)

        tab.setLayout(layout)
        self.tabs.addTab(tab, "微信管理")
        self.refresh_wechat_list()

    def save_master_name(self):
        name = self.wechat_input.text().strip()
        if name:
            self.master_wechat_name = name
            # QMessageBox.information(self, "保存成功", f"已将所有微信的主人设置为：{name}")
            QMessageBox.information(self, "保存成功", f"功能暂未实现")
        else:
            QMessageBox.warning(self, "输入无效", "请输入有效的微信名！")

    def refresh_wechat_list(self):
        self.wechat_table.setRowCount(0)
        bc.connect_wx()
        wechat_list_data = db.fetch_all(
            "SELECT bot_name, login_time, duration, pid, status, recv, send FROM bot where is_active=1 order by id asc")

        for i in range(len(wechat_list_data)):
            self.wechat_table.insertRow(i)
            print(wechat_list_data[i][0])
            self.wechat_table.setItem(i, 0, QTableWidgetItem(wechat_list_data[i][0]))
            self.wechat_table.setItem(i, 1, QTableWidgetItem(wechat_list_data[i][1]))
            self.wechat_table.setItem(i, 2, QTableWidgetItem(wechat_list_data[i][2]))
            self.wechat_table.setItem(i, 3, QTableWidgetItem(wechat_list_data[i][3]))
            self.wechat_table.setItem(i, 4, QTableWidgetItem(wechat_list_data[i][4]))
            self.wechat_table.setItem(i, 5, QTableWidgetItem(wechat_list_data[i][5]))
            self.wechat_table.setItem(i, 6, QTableWidgetItem(wechat_list_data[i][6]))

    def on_wechat_table_selected(self, selected, _):
        if selected.indexes():
            row = selected.indexes()[0].row()
            self.current_selected_wechat = self.wechat_list_data[row]
            self.setup_btn.setEnabled(True)
        else:
            self.setup_btn.setEnabled(False)

    def open_setup_window(self):
        if self.current_selected_wechat:
            dialog = QDialog(self)
            dialog.setWindowTitle(f"设置 - {self.current_selected_wechat['name']}")
            dialog.resize(400, 300)
            dialog.exec()

    def create_group_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(10)

        selector_layout = QHBoxLayout()
        selector_layout.addWidget(QLabel("选择微信账号："))
        self.wechat_combo = QComboBox()
        self.wechat_combo.addItem("请先选择一个微信")
        for data in self.wechat_list_data:
            self.wechat_combo.addItem(data['name'])
        self.load_group_btn = QPushButton("加载群聊列表")
        self.load_group_btn.clicked.connect(self.load_group_chats)
        selector_layout.addWidget(self.wechat_combo)
        selector_layout.addWidget(self.load_group_btn)
        layout.addLayout(selector_layout)

        splitter = QSplitter(Qt.Horizontal)

        left_widget = QWidget()
        left_layout = QVBoxLayout()
        left_layout.setContentsMargins(8, 8, 8, 8)
        left_layout.addWidget(QLabel("<b>📚 群聊列表</b>"))
        self.group_list = QListWidget()
        self.group_list.itemClicked.connect(self.display_group_info)
        left_layout.addWidget(self.group_list)
        left_widget.setLayout(left_layout)
        splitter.addWidget(left_widget)

        right_widget = QWidget()
        right_layout = QVBoxLayout()
        right_layout.setContentsMargins(12, 8, 12, 8)
        right_layout.addWidget(QLabel("<b>ℹ️ 群信息</b>"))
        self.group_info_label = QLabel("暂无选中群聊")
        self.group_info_label.setStyleSheet("QLabel { background: #f5f5f5; padding: 10px; border-radius: 6px; }")
        self.group_info_label.setWordWrap(True)
        right_layout.addWidget(self.group_info_label)
        right_layout.addStretch()
        right_widget.setLayout(right_layout)
        splitter.addWidget(right_widget)

        splitter.setSizes([400, 600])
        layout.addWidget(splitter)

        tab.setLayout(layout)
        self.tabs.addTab(tab, "群聊功能")

    def load_group_chats(self):
        index = self.wechat_combo.currentIndex()
        if index <= 0:
            QMessageBox.warning(self, "提示", "请先选择一个微信账号！")
            return

        self.group_list.clear()
        groups = [
            {"name": "技术交流群", "type": "普通群", "members": 230},
            {"name": "Python开发组", "type": "VIP群", "members": 156},
            {"name": "生活分享群", "type": "普通群", "members": 198},
        ]
        for g in groups:
            item = QListWidgetItem(f"👥 {g['name']} | {g['type']} | 🧑‍🤝‍🧑{g['members']}")
            item.setData(Qt.UserRole, g)
            self.group_list.addItem(item)

    def display_group_info(self, item):
        data = item.data(Qt.UserRole)
        info = (
            f"群名称：{data['name']}\n"
            f"群类型：{data['type']}\n"
            f"群人数：{data['members']}\n"
            f"授权时间：2024-01-01\n"
            f"授权类型：正式授权"
        )
        self.group_info_label.setText(info)

    def create_entertainment_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)

        self.plugin_table = QTableWidget()
        self.plugin_table.setColumnCount(6)
        self.plugin_table.setHorizontalHeaderLabels(["名称", "版本", "作者", "说明", "状态", "操作"])
        self.plugin_table.setRowCount(len(self.plugin_data))
        self.plugin_table.verticalHeader().setVisible(False)
        self.plugin_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.plugin_table.setSelectionBehavior(QTableWidget.SelectRows)
        # self.plugin_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.plugin_table.horizontalHeader().setSectionsMovable(False)
        self.plugin_table.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.plugin_table.setColumnWidth(0, 180)
        self.plugin_table.setColumnWidth(1, 150)
        self.plugin_table.setColumnWidth(2, 150)
        self.plugin_table.setColumnWidth(3, 150)
        self.plugin_table.setColumnWidth(4, 100)
        self.plugin_table.setColumnWidth(5, 150)

        for row, p in enumerate(self.plugin_data):
            self.plugin_table.setItem(row, 0, QTableWidgetItem(p['name']))
            self.plugin_table.setItem(row, 1, QTableWidgetItem(p['version']))
            self.plugin_table.setItem(row, 2, QTableWidgetItem(p['author']))
            self.plugin_table.setItem(row, 3, QTableWidgetItem(p['desc']))
            self.plugin_table.setItem(row, 4, QTableWidgetItem(p['status']))
            self.plugin_table.setItem(row, 5, QTableWidgetItem("... (功能中)"))

        # ✅ 使用 selectionModel().selectionChanged 监听选中变化
        self.plugin_table.selectionModel().selectionChanged.connect(self.on_plugin_selection_changed)

        layout.addWidget(self.plugin_table)

        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        self.reload_btn = QPushButton("🔄 重载")
        self.enable_btn = QPushButton("✅ 启用")
        self.disable_btn = QPushButton("⏹️ 停用")
        self.uninstall_btn = QPushButton("❌ 卸载")

        # 设置按钮宽度和提示
        for btn in [self.reload_btn, self.enable_btn, self.disable_btn, self.uninstall_btn]:
            btn.setFixedWidth(100)
            btn_layout.addWidget(btn)

        btn_layout.addStretch()
        layout.addLayout(btn_layout)

        # 连接事件
        self.reload_btn.clicked.connect(self.on_reload)
        self.enable_btn.clicked.connect(self.on_enable)
        self.disable_btn.clicked.connect(self.on_disable)
        self.uninstall_btn.clicked.connect(self.on_uninstall)

        # ✅ 初始化按钮状态
        self.on_plugin_selection_changed(None, None)

        tab.setLayout(layout)
        self.tabs.addTab(tab, "娱乐功能")

    def on_plugin_selection_changed(self, selected, deselected):
        """更新插件操作按钮的启用状态"""
        has_selection = len(self.plugin_table.selectedIndexes()) > 0
        self.reload_btn.setEnabled(True)
        self.enable_btn.setEnabled(has_selection)
        self.disable_btn.setEnabled(has_selection)
        self.uninstall_btn.setEnabled(has_selection)

    def on_reload(self):

        QMessageBox.information(self, "重载", "所有插件已重载。")

    def on_enable(self):
        selected = self.plugin_table.currentRow()
        if selected >= 0:
            self.plugin_table.item(selected, 4).setText("启用")
            name = self.plugin_table.item(selected, 0).text()
            QMessageBox.information(self, "启用", f"插件 {name} 已启用。")
        else:
            QMessageBox.warning(self, "提示", "请先选择一个插件。")

    def on_disable(self):
        selected = self.plugin_table.currentRow()
        if selected >= 0:
            self.plugin_table.item(selected, 4).setText("禁用")
            name = self.plugin_table.item(selected, 0).text()
            QMessageBox.information(self, "停用", f"插件 {name} 已停用。")
        else:
            QMessageBox.warning(self, "提示", "请先选择一个插件。")

    def on_uninstall(self):
        selected = self.plugin_table.currentRow()
        if selected >= 0:
            name = self.plugin_table.item(selected, 0).text()
            reply = QMessageBox.question(self, "确认卸载", f"确定要卸载插件 {name} 吗？")
            if reply == QMessageBox.Yes:
                self.plugin_data.pop(selected)
                self.plugin_table.removeRow(selected)
                QMessageBox.information(self, "卸载", f"插件 {name} 已卸载。")
        else:
            QMessageBox.warning(self, "提示", "请先选择一个插件。")

    def create_settings_tab(self):
        tab = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(40, 40, 40, 40)
        layout.addWidget(QLabel("⚙️ 系统设置"), alignment=Qt.AlignCenter)
        layout.addWidget(QLabel("功能开发中..."), alignment=Qt.AlignCenter)
        layout.addStretch()
        tab.setLayout(layout)
        self.tabs.addTab(tab, "系统设置")

    def closeEvent(self, event):
        if self.settings_manager.should_minimize_on_close():
            self.showMinimized()
            event.ignore()
        else:
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle("确认关闭")
            msg_box.setText("是否将窗口最小化到托盘？")
            msg_box.setIcon(QMessageBox.Question)
            yes_btn = msg_box.addButton("是", QMessageBox.YesRole)
            no_btn = msg_box.addButton("否", QMessageBox.NoRole)
            cancel_btn = msg_box.addButton("取消", QMessageBox.RejectRole)

            checkbox = QCheckBox("以后不再提示，直接最小化")
            msg_box.setCheckBox(checkbox)

            reply = msg_box.exec()

            if msg_box.clickedButton() == yes_btn:
                if checkbox.isChecked():
                    self.settings_manager.set_minimize_on_close(True)
                self.showMinimized()
                event.ignore()
            elif msg_box.clickedButton() == no_btn:
                if checkbox.isChecked():
                    self.settings_manager.set_minimize_on_close(True)
                event.accept()
            else:
                event.ignore()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_EnableHighDpiScaling)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)
    app.setStyle("Fusion")

    window = MainWindow()
    window.show()
    sys.exit(app.exec())
